package com.learn.mybtsp.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.learn.mybtsp.mapper.AdminUserMapper;
import com.learn.mybtsp.mapper.PermissionMapper;
import com.learn.mybtsp.mapper.RoleMapper;
import com.learn.mybtsp.pojo.AdminUser;
import com.learn.mybtsp.pojo.Permission;
import com.learn.mybtsp.pojo.Role;
import com.learn.mybtsp.security.MySimpleGrantedAuthority;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
@Component
@Slf4j
public class SecurityUserService implements UserDetailsService {

    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("登录时的username:  ", username);
        // 当用户进行登录时， springSecurity 会将请求转发到此
        LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
        // 根据用户名进行查找
        queryWrapper.eq(AdminUser::getUsername,username).last("limit 1");
        AdminUser adminUser = adminUserMapper.selectOne(queryWrapper);
        if (adminUser == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<GrantedAuthority> authorityList = new ArrayList<>();
        // 在这里对user进行设置角色并授权
        List<Role> roleList = roleMapper.findRoleListByUserId(adminUser.getId());
        for (Role role : roleList) {
            // 添加role
            // 使用了自定的MySimpleGrantedAuthority类
            authorityList.add(new MySimpleGrantedAuthority("ROLE_"+role.getRoleKeyword()));
            // 根据roleId查询出 permission
            List<Permission> permissionList = permissionMapper.findPermissionByRole(role.getId());
            for (Permission permission : permissionList) {
                // 添加permission
                // 使用了自定义的子类MySimpleGrantedAuthority，可以添加path参数
                authorityList.add(new MySimpleGrantedAuthority(permission.getPermissionKeyword(),permission.getPath()));
            }
        }

        UserDetails userDetails = new User(username,adminUser.getPassword(),authorityList);
        return userDetails;
    }
}
